//保存用户id-用户名
shanbay.user = (function() {
    var that = this;

    this.all = {};

    var save_user = function(id, name) {
        if (id in that.all) return;

        if ("users" in localStorage) {
            that.all = JSON.parse(localStorage.users);
        }
        name = $.trim(name);
        that.all[id] = name;
        localStorage.users = JSON.stringify(that.all);
    };

    this.get_name_from_urls = function(urls) {
        if ("users" in localStorage) {
            that.all = JSON.parse(localStorage.users);
        }
        
        return $.map(urls, function(url) {
            return get_name_from_url(url);
        });
    };

    var get_name_from_url = function(url) {
        var match = url.match(/review\/progress\/(\d+)/);
        if (match) {
            var id = parseInt(match[1]);
            return that.all[id];
        }
        
        match = url.match(/checkin\/user\/(\d+)/);
        if (match) {
            var id = parseInt(match[1]);
            return that.all[id];
        }

        match = url.match(/user\/list\/([^\\]+)/);
        if (match) {
            return match[1];
        }

        match = url.match(/17mail\/compose\/([^\\]+)/);
        if (match) {
            return match[1];
        }

        return null;
    };

    this.handle_user = function() {
        console.log("SE: users: " + localStorage.users);

        var url = window.location.href.replace(/(\?|#).*/, '');
        
        var match = url.match(/review\/progress\/(\d+)/);
        if (match) {
            var id = parseInt(match[1]);
            var name = $(".profile .username").text().match(/\((.*)\)/)[1];
            return save_user(id, name);
        }
        
        match = url.match(/checkin\/user\/(\d+)/);
        if (match) {
            var id = parseInt(match[1]);
            var name = $("#right-container #content-title").text().match(/(.*) 的日记/)[1];
            return save_user(id, name);
        }
    };

    return this;
})();

$(function() {
    shanbay.user.handle_user();
});
